/**
* Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.deployment.axis.wsr;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;

import org.apache.log4j.Logger;
import org.apache.xmlbeans.XmlCursor;

import cgl.narada.wsinfra.exception.DeploymentException;
import cgl.narada.wsinfra.exception.MessageFlowException;
import cgl.narada.wsinfra.exception.ProcessingException;
import cgl.narada.wsinfra.schemas.addressing.ActionDocument;
import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.schemas.addressing.FromDocument;
import cgl.narada.wsinfra.schemas.addressing.RelatesToDocument;
import cgl.narada.wsinfra.schemas.soap.EnvelopeDocument;
import cgl.narada.wsinfra.util.SoapEnvelopeConversion;
import cgl.narada.wsinfra.util.SoapMessageAlteration;
import cgl.narada.wsinfra.wsa.WsaEnvelopeCreator;
import cgl.narada.wsinfra.wsa.WsaEprCreator;
import cgl.narada.wsinfra.wsa.WsaProcessingFactory;
import cgl.narada.wsinfra.wsr.WsrActions;
import cgl.narada.wsinfra.wsr.WsrQNames;

/** 
 * @author Sima Patel
 * @version 1.0
 * $Revision: 1.0 $ 
 * This acts as Application at WsrSource Proxy Web Service. It will initiates
 * all requests for Wsr Source using Frame.
 */

public class WsrSourceClientFrame{
    private WsaEprCreator wsaEprCreator;

    private WsaEnvelopeCreator wsaEnvelopeCreator;

    private SoapEnvelopeConversion soapEnvelopeConversion;

    private SoapMessageAlteration soapMessageAlteration;

    private WsrSourceClientService wsrSourceClientService;

    private WsrActions wsrActions;

    private int tracker;

    private String moduleName = "WsrSourceClientFrame :";

    private static String sinkAddress;

    private static String sourceAddress;
    
    JFrame frame;
    JPanel panel;

    JLabel replyToLabel;
    JLabel groupIdLabel;
    JLabel label1;
    JLabel label2;
    JLabel label3;
    JLabel label4;
    JLabel label5;
    JLabel label6;
    JLabel label7;
    JLabel label8;
       
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button4;
    JButton button5;
    JButton button6;
    JButton button7;
    JButton button8;
       
    JTextField textField12;
    JTextField textField22;
    JTextField textField32;
    JTextField textField42;
    JTextField textField51;
    JTextField textField52;
    JTextField textField61;
    JTextField textField62;
    JTextField textField72;
    JTextField textField82;
    static WsrSourceClientFrame f;
    static Logger logger = Logger.getLogger(WsrSourceClientFrame.class);
    
    public WsrSourceClientFrame(){

      sinkAddress = WsrServicesFactory.getSinkAddress();
      sourceAddress = WsrServicesFactory.getSourceAddress();
      wsrActions = WsrActions.getInstance();
      wsaEprCreator = WsaProcessingFactory.getWsaEprCreator();
      wsaEnvelopeCreator = WsaProcessingFactory.getWsaEnvelopeCreator();
      wsrSourceClientService = new WsrSourceClientService();
      soapEnvelopeConversion = SoapEnvelopeConversion.getInstance();
      soapMessageAlteration = SoapMessageAlteration.getInstance();

      frame = new JFrame();
      WindowListener wl = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
           System.exit(0);
      }
      };
      frame.addWindowListener(wl);

      panel = new JPanel();
      frame.getContentPane().add(panel);
      GridBagLayout gridbag = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
      panel.setLayout(gridbag);
      
      label1 = new JLabel("1. Response-Reply Pattern & Last Message = " +
      										"false & optional groupId ");
      panel.add(label1);
      constraints.gridx = 0;
      constraints.gridy = 1;
      gridbag.setConstraints(label1, constraints);

      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy = 4;
      gridbag.setConstraints(groupIdLabel, constraints);

      textField12 = new JTextField(28);
      panel.add(textField12);
      constraints.gridx = 1;
      constraints.gridy =4;
      gridbag.setConstraints(textField12, constraints);

      button1 = new JButton("Submit");
      button1.addActionListener(new Button1Handler());
      panel.add(button1);
      constraints.gridx = 2;
      constraints.gridy = 4;
      gridbag.setConstraints(button1, constraints);

      label2 = new JLabel("2. Response-Reply Pattern & Last Message = " +
      											"true & optional groupId ");
      panel.add(label2);
      constraints.gridx = 0;
      constraints.gridy = 9;
      gridbag.setConstraints(label2, constraints);
      
      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy = 13;
      gridbag.setConstraints(groupIdLabel, constraints);

      textField22 = new JTextField(28);
      panel.add(textField22);
      constraints.gridx = 1;
      constraints.gridy =13;
      gridbag.setConstraints(textField22, constraints);

      button2 = new JButton("Submit");
      button2.addActionListener(new Button2Handler());
      panel.add(button2);
      constraints.gridx = 2;
      constraints.gridy = 13;
      constraints.insets = new Insets(10,10,10,10);
      gridbag.setConstraints(button2, constraints);

      label3 = new JLabel("3. Callback-Reply Pattern & Last Message = " +
      										"false & optional groupId ");
      panel.add(label3);
      constraints.gridx = 0;
      constraints.gridy = 17;
      gridbag.setConstraints(label3, constraints);

      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy = 21;
      gridbag.setConstraints(groupIdLabel, constraints);
      
      textField32 = new JTextField(28);
      panel.add(textField32);
      constraints.gridx = 1;
      constraints.gridy =21;
      gridbag.setConstraints(textField32, constraints);

      button3 = new JButton("Submit");
      button3.addActionListener(new Button3Handler());
      panel.add(button3);
      constraints.gridx = 2;
      constraints.gridy = 21;
      gridbag.setConstraints(button3, constraints);
      
      label4 = new JLabel("4. Callback-Reply Pattern & Last Message = " +
      											"true & optional groupId ");
      panel.add(label4);
      constraints.gridx = 0;
      constraints.gridy = 25;
      gridbag.setConstraints(label4, constraints);

      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy = 29;
      gridbag.setConstraints(groupIdLabel, constraints);
      
      textField42 = new JTextField(28);
      panel.add(textField42);
      constraints.gridx = 1;
      constraints.gridy =29;
      gridbag.setConstraints(textField42, constraints);

      button4 = new JButton("Submit");
      button4.addActionListener(new Button4Handler());
      panel.add(button4);
      constraints.gridx = 2;
      constraints.gridy = 29;
      gridbag.setConstraints(button4, constraints);

      label5 = new JLabel("5. Callback-Reply Pattern & Last Message = " +
      					"false & optional Reply-To & optional groupId  ");
      panel.add(label5);
      constraints.gridx = 0;
      constraints.gridy = 33;
      gridbag.setConstraints(label5, constraints);

      replyToLabel = new JLabel("Reply-To");
      panel.add(replyToLabel);
      constraints.gridx = 0;
      constraints.gridy = 37;
      gridbag.setConstraints(replyToLabel, constraints); 

      textField51 = new JTextField(28);
      panel.add(textField51);
      constraints.gridx = 1;
      constraints.gridy =37;
      gridbag.setConstraints(textField51, constraints);

      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy =41;
      gridbag.setConstraints(groupIdLabel, constraints);

      textField52 = new JTextField(28);
      panel.add(textField52);
      constraints.gridx = 1;
      constraints.gridy = 41;
      gridbag.setConstraints(textField52, constraints);

      button5 = new JButton("Submit");
      button5.addActionListener(new Button5Handler());
      panel.add(button5);
      constraints.gridx = 2;
      constraints.gridy = 41;
      gridbag.setConstraints(button5, constraints);

      label6 = new JLabel("6. Callback-Reply Pattern & Last Message = " +
      					"true & optional Reply-To & optional groupId  ");
      panel.add(label6);
      constraints.gridx = 0;
      constraints.gridy = 45;
      gridbag.setConstraints(label6, constraints);

      replyToLabel = new JLabel("Reply-To");
      panel.add(replyToLabel);
      constraints.gridx = 0;
      constraints.gridy = 49;
      gridbag.setConstraints(replyToLabel, constraints); 


      textField61 = new JTextField(28);
      panel.add(textField61);
      constraints.gridx = 1;
      constraints.gridy =49;
      gridbag.setConstraints(textField61, constraints);

      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy = 53;
      gridbag.setConstraints(groupIdLabel, constraints);


      textField62 = new JTextField(28);
      panel.add(textField62);
      constraints.gridx = 1;
      constraints.gridy =53;
      gridbag.setConstraints(textField62, constraints);

      button6 = new JButton("Submit");
      button6.addActionListener(new Button6Handler());
      panel.add(button6);
      constraints.gridx = 2;
      constraints.gridy = 53;
      gridbag.setConstraints(button6, constraints);
      
      label7 = new JLabel("7. Poll-Reply Pattern & Last Message = " +
      										"false & optional groupId  ");
      panel.add(label7);
      constraints.gridx = 0;
      constraints.gridy = 57;
      gridbag.setConstraints(label7, constraints);

      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy = 61;
      gridbag.setConstraints(groupIdLabel, constraints);

      textField72 = new JTextField(28);
      panel.add(textField72);
      constraints.gridx = 1;
      constraints.gridy =61;
      gridbag.setConstraints(textField72, constraints);

      button7 = new JButton("Submit");
      button7.addActionListener(new Button7Handler());
      panel.add(button7);
      constraints.gridx = 2;
      constraints.gridy = 61;
      gridbag.setConstraints(button7, constraints);

          
      label8 = new JLabel("8. Poll-Reply Pattern & Last Message = " +
      										"true  & optional groupId  ");
      panel.add(label8);
      constraints.gridx = 0;
      constraints.gridy = 65;
      gridbag.setConstraints(label8, constraints);   
      
      groupIdLabel = new JLabel("Group-ID");
      panel.add(groupIdLabel);
      constraints.gridx = 0;
      constraints.gridy = 69;
      gridbag.setConstraints(groupIdLabel, constraints);

      textField82 = new JTextField(28);
      panel.add(textField82);
      constraints.gridx = 1;
      constraints.gridy =69;
      gridbag.setConstraints(textField82, constraints);     

      button8 = new JButton("Submit");
      button8.addActionListener(new Button8Handler());
      panel.add(button8);
      constraints.gridx = 2;
      constraints.gridy = 69;
      gridbag.setConstraints(button8, constraints);   

     
      frame.pack();
      frame.setVisible(true);

 }
 /**
 * This method will send SOAPMessage to Network
 * @param soapMessage
 * @throws DeploymentException
 * @throws MessageFlowException
 * @throws ProcessingException
 */
 public void sendSOAPMessage(SOAPMessage soapMessage)
             throws DeploymentException, MessageFlowException,
             ProcessingException {
     wsrSourceClientService.enrouteToNetwork(soapMessage);
 }
 /**
 * This method will create SOAPMessage based on given paramters.
 * @param source
 * @param sink
 * @param groupId
 * @param replyPattern
 * @param replyTo
 * @param lastMessage
 * @return SOAPMessage
 */
 public SOAPMessage createSOAPMessage(String source, String sink,
                            String groupId, String replyPattern, String replyTo,
                                      String lastMessage) {

     EndpointReferenceType sourceEpr = wsaEprCreator.createEpr(source);

     EndpointReferenceType sinkEpr = wsaEprCreator.createEpr(sink);
        
     FromDocument from = FromDocument.Factory.newInstance();
     from.setFrom(sourceEpr);
     ActionDocument action = ActionDocument.Factory.newInstance();
     action.addNewAction().setStringValue(wsrActions.getProcessRequest());
     RelatesToDocument relatesTo = null;

     EnvelopeDocument envelopeDocument = wsaEnvelopeCreator
                 .createSoapEnvelope(sinkEpr, from, action, relatesTo);

 String messageType=WsrServicesFactory.getApplicationMessage();
        QName qnameType=new QName("http://www.naradabrokering.org",messageType);
        
        XmlCursor headerCursor = envelopeDocument.getEnvelope().getHeader()
        .newCursor();
        //tracker++;
        String value1 = "Tracker :" + Math.random();
        headerCursor.toNextToken();
        headerCursor.insertElementWithText(qnameType, value1);
        headerCursor.dispose();
        
        
     QName qname = new QName("http://www.naradabrokering.org",
                "Application-Content");
     XmlCursor bodyCursor = envelopeDocument.getEnvelope().getBody()
                .newCursor();
     tracker++;
     String value = "Tracker :" + tracker;
     bodyCursor.toNextToken();
     bodyCursor.insertElementWithText(qname, value);
     bodyCursor.dispose();
        

     if (groupId != null) {
            QName qName = WsrQNames.getInstance().getGroupId();
            boolean added = soapMessageAlteration.addToSoapHeader(
                    envelopeDocument, qName, groupId);
	    
     }
     if (replyPattern != null) {
         QName qName = WsrQNames.getInstance().getRPattern();
         boolean added = soapMessageAlteration.addToSoapHeader(
                    envelopeDocument, qName, replyPattern);
	   
     }
     if (replyTo != null) {
         QName qName = WsrQNames.getInstance().getReplyTo();
         boolean added = soapMessageAlteration.addToSoapHeader(
                    envelopeDocument, qName, replyTo);
     }
     if (lastMessage != null) {
         QName qName = WsrQNames.getInstance().getLastMessage();
         boolean added = soapMessageAlteration.addToSoapHeader(
                    envelopeDocument, qName, lastMessage);
	    
     }
     System.out.println("********* SOAP Message by Source Client  ********\n\n"+
    		 									envelopeDocument.toString());
     SOAPMessage soapMessage = null;
     try {
         soapMessage = soapEnvelopeConversion
                    .getSOAPMessage(envelopeDocument);
     } catch (ProcessingException ex) {
          String errorReport ="Problems converting to javax.xml.SOAPMessage\n"
                    + ex.toString();
          System.out.println(errorReport);
     }
     return soapMessage;

  }  
  
  public static void main(String[] args) {
        f = new WsrSourceClientFrame();
  }


  class Button1Handler implements ActionListener{
      public void actionPerformed(ActionEvent e){
	  String groupId = null;
          if (textField12.getText().trim().length() > 0){
	      groupId = textField12.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage
	      	( sourceAddress, sinkAddress, groupId,"Response", null, "false");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e1){
              e1.printStackTrace();
          }
      }
  }
  class Button2Handler implements ActionListener{
      public void actionPerformed(ActionEvent e) {
        String groupId = null;
          if (textField22.getText().trim().length() > 0){
	      groupId = textField22.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage
	      ( sourceAddress, sinkAddress, groupId,"Response", null, "true");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e2){
              e2.printStackTrace();
          } 
      }
  }
  class Button3Handler implements ActionListener{
      public void actionPerformed(ActionEvent e) {
        String groupId = null;
          if (textField32.getText().trim().length() > 0){
	      groupId = textField32.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage
	      ( sourceAddress, sinkAddress, groupId,"Callback", null, "false");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e3){
              e3.printStackTrace();
          } 
      }
  }
  class Button4Handler implements ActionListener{
      public void actionPerformed(ActionEvent e) {
        String groupId = null;
          if (textField42.getText().trim().length() > 0){
	      groupId = textField42.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage
	      ( sourceAddress, sinkAddress, groupId,"Callback", null, "true");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e4){
              e4.printStackTrace();
          } 
      }
  }
  class Button5Handler implements ActionListener{
      public void actionPerformed(ActionEvent e) {
	String replyTo = null;
        String groupId = null;
	 if (textField51.getText().trim().length() > 0){
	      replyTo = textField51.getText().trim();
          }
          if (textField52.getText().trim().length() > 0){
	      groupId = textField52.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage
	      ( sourceAddress, sinkAddress, groupId,"Callback",replyTo, "false");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e5){
              e5.printStackTrace();
          } 
      }
  }
   class Button6Handler implements ActionListener{
      public void actionPerformed(ActionEvent e) {
	String replyTo = null;
        String groupId = null;
	 if (textField61.getText().trim().length() > 0){
	      replyTo = textField61.getText().trim();
          }
          if (textField62.getText().trim().length() > 0){
	      groupId = textField62.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage
	      (sourceAddress, sinkAddress, groupId,"Callback",replyTo, "true");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e6){
              e6.printStackTrace();
          } 
      }
  }
   class Button7Handler implements ActionListener{
      public void actionPerformed(ActionEvent e) {
        String groupId = null;
          if (textField72.getText().trim().length() > 0){
	      groupId = textField72.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage
	      ( sourceAddress, sinkAddress, groupId,"Poll", null, "false");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e7){
              e7.printStackTrace();
          } 
      }
  }
     class Button8Handler implements ActionListener{
      public void actionPerformed(ActionEvent e) {
        String groupId = null;
          if (textField82.getText().trim().length() > 0){
	      groupId = textField82.getText().trim();
          }
	  try{
	      SOAPMessage soapMessage = f.createSOAPMessage(
	    		  sourceAddress, sinkAddress, groupId,"Poll", null, "true");
	      f.sendSOAPMessage(soapMessage);
	  }catch(Exception e8){
              e8.printStackTrace();
          } 
      }
  }
  
}






